package com.lwm.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSignerUtil;

import java.util.Map;

/**
 * JWT工具类
 * 对 HuTool 的JWT工具类的二次封装
 */
public class JWTUtils {

    /**
     * 密钥
     */
    private static final String KEY = "qmcx";

    /**
     * 当前时间
     */
    private static final DateTime NOW_TIME = DateTime.now();

    /**
     * 过期时间
     */
    private static final DateTime EXPIRES_TIME = NOW_TIME.offsetNew(DateField.HOUR, 3);

    /**
     * 创建Token
     *
     * @param map 封装map集合的数据
     * @return {@link String}
     */
    public static String createToken(Map<String, Object> map) {
        map.put("expire_time", EXPIRES_TIME);
        return JWTUtil.createToken(map, JWTSignerUtil.hs256(KEY.getBytes()));
    }

    /**
     * 解析Token
     *
     * @param token Token
     */
    public static JWTPayload parseToken(String token) throws Exception{
        JWT jwt = JWTUtil.parseToken(token).setSigner(JWTSignerUtil.hs256(KEY.getBytes()));
        if (!jwt.verify()) throw new RuntimeException("token 非法");
        if (!jwt.validate(0)) throw new RuntimeException("token 过期，请重新登录");

        return jwt.getPayload();
    }

    public static void main(String[] args) {
        // Map<String, Object> map = new HashMap<>();
        // map.put("id","6661");
        // map.put("expire_time", EXPIRES_TIME);
        // String token = createToken(map);
        // System.out.println(token);
        try {
            JWTPayload jwtPayload = parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHBpcmVfdGltZSI6MTY5MDExMTk3NywiaWQiOiIxIn0.FnNWWrTTJEyFH0ob-hjhFoA1iT9uqGd8tLCJqoU9ejU");
            System.out.println(DateUtil.date(Long.parseLong(jwtPayload.getClaim("expire_time").toString()) * 1000));
            System.out.println(jwtPayload.getClaim("id"));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token 非法");
        }
    }
}
